package cc.rengu.igas.mcps.core.service.trans.scanpay;

import cc.rengu.igas.mcps.common.constant.McpsParamConstant;
import cc.rengu.igas.mcps.common.enums.QrBindStatusEnum;
import cc.rengu.igas.mcps.common.enums.RespCodeEnum;
import cc.rengu.igas.mcps.common.util.ImageUtil;
import cc.rengu.igas.mcps.common.util.QrCodeUtil;
import cc.rengu.igas.mcps.core.service.base.ManageService;
import cc.rengu.igas.mcps.facade.bean.OrderInfoBean;
import cc.rengu.igas.mcps.facade.bean.TermInfo;
import cc.rengu.igas.mcps.facade.request.QrCodeInfoQueryRequeset;
import cc.rengu.igas.mcps.facade.response.QrCodeInfoQueryResponse;
import cc.rengu.igas.share.core.model.QrCodeInfo;
import cc.rengu.igas.share.core.realize.BompService;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.BompServiceImpl;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.MchntOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.SysParamMapper;
import cc.rengu.oltp.service.common.dao.UserOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.MchntOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.SysParamMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.UserOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.BaseProdEnum;
import cc.rengu.oltp.service.common.enums.BizStatusEnum;
import cc.rengu.oltp.service.common.enums.OrderStatusEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 二维码信息查询服务,只有动态码和静态码校验C1码签名
 *
 * @author panky
 * modify by wangcheng 2021-09-13
 **/
public class McpsQrCodeInfoQueryService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        QrCodeInfoQueryRequeset qrCodeInfoQueryRequeset = new QrCodeInfoQueryRequeset();
        ConvertUtil.convertOutput(qrCodeInfoQueryRequeset);
        return qrCodeInfoQueryRequeset;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {

        QrCodeInfoQueryRequeset queryRequeset = (QrCodeInfoQueryRequeset) request;
        String instId = queryRequeset.getHeader().getInstId();
        String qrUrl = URLDecoder.decode(queryRequeset.getQrUrl());

        /*判断是否银标码：收银台域名?qrCode=https//95516.com/xxxx*/
        int qrIndex = qrUrl.indexOf("qrCode=");
        if (qrIndex > 0) {
            qrUrl = qrUrl.substring(qrIndex + 7);
            /*银联回调时url编码了,此时urldecode*/
            qrUrl = URLDecoder.decode(qrUrl, "UTF-8");
        }
        rglog.info("实际二维码url<{}>", qrUrl);

        //先将二维码类型赋值为他行行，然后再根据inf信息转换成本行的动态或者静态码
        String qrCodeType = "T";
        int lastIndex = qrUrl.lastIndexOf("inf=");
        if (lastIndex > -1) {
            qrCodeType = qrUrl.substring(lastIndex + 4, lastIndex + 5);
        }

        //判断该二维码信息属于动态码还是静态码
        QrCodeInfoQueryResponse queryResponse = new QrCodeInfoQueryResponse();
        queryResponse.setQrType(qrCodeType);
        OrderInfoBean orderInfo;
        switch (qrCodeType) {
            case "D": {
                //去掉C1码中的tt和si参数
                qrUrl = QrCodeUtil.filterTtAndSi(qrUrl);
                rglog.info("过滤C1码参数后url，instId:<{}>,qrUrl:<{}>", instId, qrUrl);

                //查询用户订单表获取订单信息
                UserOrderInfoMapper userOrderInfoMapper = new UserOrderInfoMapperImpl();
                UserOrderInfo userOrderInfo = userOrderInfoMapper.selectUserOrderInfoByOrderUrl(instId, qrUrl);
                if (userOrderInfo == null) {
                    rglog.error("用户订单表中不存在该动态二维码交易记录,instId:<{}>,orderUrl:<{}>", instId, qrUrl);
                    throw new BizException(RespCodeEnum.ORDER_NOEXIT.getRespCode(), RespCodeEnum.ORDER_NOEXIT.getRespDesc());
                } else if (OrderStatusEnum.FINISH.getStatus().equals(userOrderInfo.getOrderStatus())) {
                    rglog.error("订单已经支付完成，不能重复支付!");
                    throw new BizException(RespCodeEnum.ORDER_ALREADY_PAY.getRespCode(), RespCodeEnum.ORDER_ALREADY_PAY.getRespDesc());
                }

                //获取商户订单信息
                MchntOrderInfoMapper mchntOrderInfoMapper = new MchntOrderInfoMapperImpl();
                List<MchntOrderInfo> mchntOrderInfos = mchntOrderInfoMapper.selectMchntOrderInfoBySysSeqNum(userOrderInfo.getInstId(), userOrderInfo.getSysSeqNum());
                if (null == mchntOrderInfos || mchntOrderInfos.isEmpty()) {
                    rglog.info("商户订单表中不存在该笔订单信息");
                    throw new BizException(RespCodeEnum.ORDER_NOEXIT.getRespCode(), RespCodeEnum.ORDER_NOEXIT.getRespDesc());
                }

                //设置orderInfo
                orderInfo = convOrderInfo(userOrderInfo, mchntOrderInfos);
                queryResponse.setUserOrderId(orderInfo.getUserOrderId());
                queryResponse.setMchntNo(orderInfo.getMchntNo());
                queryResponse.setMchntName(orderInfo.getMchntName());
                queryResponse.setOrderInfo(orderInfo);
                break;
            }
            case "S": {
                //去掉C1码中的tt和si参数
                qrUrl = QrCodeUtil.filterTtAndSi(qrUrl);
                rglog.info("过滤C1码参数后url，instId:<{}>,qrUrl:<{}> si:<{}>", instId, qrUrl);

                //查询二维码信息表获取二维码信息
                BompService bompService = new BompServiceImpl();
                QrCodeInfo qrCodeInfo = bompService.getQrCodeInfo(instId, qrUrl, null);
                String currentTime = DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS");
                if (null == qrCodeInfo || !McpsParamConstant.QR_STATUS_NORMAL.equals(qrCodeInfo.getQrStatus())) {
                    rglog.info("二维码信息不存在或二维码已停用");
                    throw new BizException(RespCodeEnum.GET_QRCODE_INVALID.getRespCode(), RespCodeEnum.GET_QRCODE_INVALID.getRespDesc());
                } else if (QrBindStatusEnum.UNBIND.getBindStatus().equals(qrCodeInfo.getBindStatus())) {
                    rglog.info("当前二维码未绑定商户，不可用.qrCodeBindStatus:<{}>", qrCodeInfo.getBindStatus());
                    throw new BizException(RespCodeEnum.GET_QRCODE_INVALID.getRespCode(), RespCodeEnum.GET_QRCODE_INVALID.getRespDesc());
                } else if (!StringUtil.isEmptyOrNull(qrCodeInfo.getEffectiveTime())
                        && DateUtil.compareTime(currentTime, qrCodeInfo.getEffectiveTime(), "yyyy-MM-dd HH:mm:ss.SSS") < 0) {
                    rglog.error("二维码未生效!");
                    throw new BizException(RespCodeEnum.GET_QRCODE_INVALID.getRespCode(), RespCodeEnum.GET_QRCODE_INVALID.getRespDesc());
                } else if (!StringUtil.isEmptyOrNull(qrCodeInfo.getExpiryTime())
                        && DateUtil.compareTime(currentTime, qrCodeInfo.getExpiryTime(), "yyyy-MM-dd HH:mm:ss.SSS") > 0) {
                    rglog.error("二维码已失效!");
                    throw new BizException(RespCodeEnum.GET_QRCODE_INVALID.getRespCode(), RespCodeEnum.GET_QRCODE_INVALID.getRespDesc());
                }

                // 创建并登记订单
                OrderService orderService = new OrderServiceImpl();
                UserOrderInfo userOrderInfo = createUserOrderInfo(queryRequeset, qrCodeInfo);
                userOrderInfo.setUserOrderId(orderService.generateUserOrderId());
                List<MchntOrderInfo> mchntOrderInfoList = createMchntOrderInfo(queryRequeset, qrCodeInfo);
                if (!orderService.registerOrderInfo(userOrderInfo, mchntOrderInfoList, null)) {
                    rglog.error("登记用户及商户订单失败!");
                    throw new BizException(RespCodeEnum.INSERT_ORDER_INFO_ERROR.getRespCode(), RespCodeEnum.INSERT_ORDER_INFO_ERROR.getRespDesc());
                }

                // 静态码允许的最大交易金额
                SysParamMapper sysParamMapper = new SysParamMapperImpl();
                SysParam staticMaxAmount = sysParamMapper.selectSysParamByPrimaryKey(instId, McpsParamConstant.OPMS_PARAM_TYPE, McpsParamConstant.STATIC_MAX_AMOUNT);
                if (staticMaxAmount != null && !StringUtil.isEmptyOrNull(staticMaxAmount.getParamValue())) {
                    queryResponse.setStaticLimitAmt(staticMaxAmount.getParamValue());
                } else {
                    queryResponse.setStaticLimitAmt(McpsParamConstant.STATIC_DEFAULT_MAX_AMOUNT);
                }

                //设置响应值,二维码URL直接返回图片内容
                orderInfo = convOrderInfo(userOrderInfo, mchntOrderInfoList);
                queryResponse.setUserOrderId(orderInfo.getUserOrderId());
                if (!StringUtil.isEmptyOrNull(qrCodeInfo.getLogoUrlPath())) {
                    queryResponse.setLogoUrl(downImage(queryRequeset, qrCodeInfo.getLogoUrlPath()));
                }
                queryResponse.setMchntName(mchntInfo.getMchntName());
                queryResponse.setMchntNo(qrCodeInfo.getMchntNo());
                queryResponse.setQrCodeName(qrCodeInfo.getQrCodeName());
                queryResponse.setOrderInfo(orderInfo);
                break;
            }
            case "T": {
                //查询用户订单表获取订单信息
                UserOrderInfoMapper userOrderInfoMapper = new UserOrderInfoMapperImpl();
                UserOrderInfo userOrderInfo = userOrderInfoMapper.selectUserOrderInfoByOrderUrl(instId, queryRequeset.getQrUrl());
                if (userOrderInfo == null) {
                    rglog.error("用户订单表中不存在他行二维码交易记录,instId:<{}>,orderUrl:<{}>", instId, qrUrl);
                    throw new BizException(RespCodeEnum.ORDER_NOEXIT.getRespCode(), RespCodeEnum.ORDER_NOEXIT.getRespDesc());
                }
                orderInfo = convOrderInfo(userOrderInfo, null);
                //设置二维码类型
                JSONObject jsonObject = JSON.parseObject(userOrderInfo.getOrderExtraInfo());
                queryResponse.setUserOrderId(orderInfo.getUserOrderId());
                queryResponse.setQrType(jsonObject.get("qrCodeType").toString());
                queryResponse.setMchntName(userOrderInfo.getGroupMchntName());
                // 他行银联二维码改成固定的二维码
                queryResponse.setMchntNo(AppParamConstant.DEFAULT_INSTID);
                queryResponse.setOrderInfo(orderInfo);
                queryResponse.setQrCodeName("银联二维码");
                break;
            }
            default:
                rglog.error("二维码<{}>格式错误", qrUrl);
                throw new BizException(RespCodeEnum.GET_QRCODE_INVALID.getRespCode(), RespCodeEnum.GET_QRCODE_INVALID.getRespDesc());
        }
        // 判断金额如果是0，或者空，设定成0.00
        if (queryResponse.getOrderInfo() != null
                && (StringUtil.isEmptyOrNull(queryResponse.getOrderInfo().getOrderAmt())
                || AmountUtil.compare("0", queryResponse.getOrderInfo().getOrderAmt()) == 0)) {
            queryResponse.getOrderInfo().setOrderAmt("0.00");
        }
        //组响应实体
        BizResponse<QrCodeInfoQueryResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(queryResponse);
        return bizResponse;
    }

    /**
     * 转换接口订单信息
     *
     * @param userOrderInfo      用户订单信息
     * @param mchntOrderInfoList 商户订单信息
     * @return 接口要返回的订单信息
     * @throws Exception 异常
     */
    private OrderInfoBean convOrderInfo(UserOrderInfo userOrderInfo, List<MchntOrderInfo> mchntOrderInfoList) throws Exception {
        OrderInfoBean orderInfoBean = new OrderInfoBean();
        String mchntNo = userOrderInfo.getGroupMchntNo();
        String mchntName = userOrderInfo.getGroupMchntName();
        String refundAmt = "0.00";
        if (null != mchntOrderInfoList) {
            if (mchntOrderInfoList.size() <= 1) {
                mchntNo = mchntOrderInfoList.get(0).getMchntNo();
                mchntName = mchntOrderInfoList.get(0).getMchntName();
            }
            /* 计算退款金额 */
            for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
                refundAmt = AmountUtil.addition(refundAmt, StringUtil.isEmptyOrNull(mchntOrderInfo.getRefundAmt()) ? "0.00" : mchntOrderInfo.getRefundAmt());
            }
        }
        /* 微信支付宝扫码商户名称显示规则：有二级商户名称显示二级商户名称,无二级商户名称显示一级商户简称 */
        MchntService mchntService = new MchntServiceImpl();
        mchntInfo = mchntService.getMchntInfo(userOrderInfo.getInstId(), mchntNo);
        if (null != mchntInfo && "11".equals(mchntInfo.getMchntType()) && StringUtil.isEmptyOrNull(mchntInfo.getMchntName())) {
            //连锁商户门店即二级商户的名称为空时，显示连锁商户即一级商户简称
            mchntInfo = mchntService.getMchntInfo(userOrderInfo.getInstId(), mchntInfo.getChainMchntNo());
            SysParamMapper sysParamMapper = new SysParamMapperImpl();
            SysParam sysParam = sysParamMapper.selectSysParamByPrimaryKey(userOrderInfo.getInstId(), McpsParamConstant.OPMS_PARAM_TYPE, McpsParamConstant.MCHNT_SIMPLE_NAME_KEY);
            if (sysParam != null && sysParam.getParamValue().equals("1") && !StringUtil.isEmptyOrNull(mchntInfo.getMchntSimpleName())) {
                //开通简称设置并且连锁商户简称不为空
                mchntName = mchntInfo.getMchntSimpleName();
            } else {
                //显示连锁商户名称
                mchntName = mchntInfo.getMchntName();
            }
        }
        orderInfoBean.setTransDate(userOrderInfo.getTxnDate());
        orderInfoBean.setTransTime(userOrderInfo.getTxnTime());
        orderInfoBean.setTxnNum(userOrderInfo.getTxnNum());
        orderInfoBean.setMchntNo(mchntNo);
        orderInfoBean.setUserOrderId(userOrderInfo.getUserOrderId());
        orderInfoBean.setMchntOrderId(userOrderInfo.getMchntOrderId());
        orderInfoBean.setMchntName(mchntName);
        orderInfoBean.setPayAcctNo("");
        orderInfoBean.setOrderCcy("156");
        orderInfoBean.setOrderAmt(userOrderInfo.getOrderAmt());
        orderInfoBean.setRefundAmt(refundAmt);
        orderInfoBean.setOrderExpiryTime(userOrderInfo.getOrderExpiryTime());
        orderInfoBean.setOrderStatus(userOrderInfo.getOrderStatus());
        orderInfoBean.setBizStatus(userOrderInfo.getBizStatus());
        orderInfoBean.setOrderDesc(userOrderInfo.getOrderDesc());
        return orderInfoBean;
    }

    /**
     * 用户订单生成
     *
     * @param queryRequeset 请求信息
     * @param qrCodeInfo    静态二维码信息
     * @return 用户订单信息
     * @throws Exception 异常
     */
    private UserOrderInfo createUserOrderInfo(QrCodeInfoQueryRequeset queryRequeset, QrCodeInfo qrCodeInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        UserOrderInfo userOrderInfo = new UserOrderInfo();
        userOrderInfo.setInstId(queryRequeset.getHeader().getInstId());// 机构标识
        userOrderInfo.setTxnDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));// 交易日期
        userOrderInfo.setTxnTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));// 交易时间
        userOrderInfo.setTxnNum(queryRequeset.getHeader().getTxnNum());// 内部交易码
        userOrderInfo.setBizType(queryRequeset.getHeader().getBizType());// 业务细分
        userOrderInfo.setMsgSrcId(queryRequeset.getHeader().getSrcSysId());// 源系统标识
        userOrderInfo.setTransChannelId(queryRequeset.getHeader().getChanlId());//请求业务渠道
        userOrderInfo.setMchntOrderId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM)); // 商户订单号不存子啊，使用系统流水号
        userOrderInfo.setUserId(""); //用户标识在支付时进行更新
        userOrderInfo.setSysSeqNum(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM));// 系统流水号
        userOrderInfo.setOrderCreateTime(DateUtil.getCurrentDateTime("yyyyMMddHHmmss"));// 订单创建时间
        userOrderInfo.setOrderAmt(!StringUtil.isEmptyOrNull(qrCodeInfo.getTransAmt()) ? qrCodeInfo.getTransAmt() : "0.00");
        userOrderInfo.setRealPayAmt(userOrderInfo.getOrderAmt());
        userOrderInfo.setOrderCcy("156");
        userOrderInfo.setOrderUrl(qrCodeInfo.getQrUrl());
        // 静态码  银联返回的静态码值为1，返回结果静态码值为0
        Map<String, String> orderExtraInfo = new HashMap<>();
        orderExtraInfo.put("qrCodeType", "0");
        userOrderInfo.setOrderExtraInfo(JSON.toJSONString(orderExtraInfo));
        // 订单有效时间,默认是30分钟
        userOrderInfo.setOrderExpiryTime(DateUtil.getDateByTimeStamp(System.currentTimeMillis() + 1800 * 1000, "yyyyMMddHHmmss"));
        userOrderInfo.setOrderStatus(OrderStatusEnum.INIT.getStatus());
        userOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        // 01-业务处理中 40-授权未完成【待密码认证】
        userOrderInfo.setBizStatus(BizStatusEnum.INIT.getStatus());
        userOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        return userOrderInfo;
    }

    /**
     * 创建商户订单
     *
     * @param queryRequeset 请求信息
     * @param qrCodeInfo    静态二维码信息
     * @return 商户订单信息
     * @throws Exception 异常
     */
    private List<MchntOrderInfo> createMchntOrderInfo(QrCodeInfoQueryRequeset queryRequeset, QrCodeInfo qrCodeInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        List<MchntOrderInfo> mchntOrderList = new ArrayList<>();
        MchntOrderInfo mchntOrderInfo = new MchntOrderInfo();
        mchntOrderInfo.setInstId(queryRequeset.getHeader().getInstId());
        mchntOrderInfo.setTxnDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));
        mchntOrderInfo.setTxnTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));
        mchntOrderInfo.setTxnNum(queryRequeset.getHeader().getTxnNum());
        mchntOrderInfo.setBizType(queryRequeset.getHeader().getBizType());
        mchntOrderInfo.setBizProdCode(BaseProdEnum.SCAN_CODE.getProdCode());
        mchntOrderInfo.setSysSeqNum(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM));
        mchntOrderInfo.setMchntOrderId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM));
        /*根据商户号获取商户信息*/
        MchntService mchntService = new MchntServiceImpl();
        mchntInfo = mchntService.getMchntInfo(queryRequeset.getHeader().getInstId(), qrCodeInfo.getMchntNo());
        if (null == mchntInfo) {
            rglog.info("商户<{}>不存在或者状态异常!", qrCodeInfo.getMchntNo());
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        mchntOrderInfo.setAcqInstCode(mchntInfo.getSignInstId());
        mchntOrderInfo.setIndustryType(mchntInfo.getIndustryType());
        mchntOrderInfo.setMchntNo(mchntInfo.getMchntNo());
        mchntOrderInfo.setMchntName(mchntInfo.getMchntName());
        mchntOrderInfo.setUserId(qrCodeInfo.getUserId());
        mchntOrderInfo.setOrderCcy("156");
        mchntOrderInfo.setOrderAmt(!StringUtil.isEmptyOrNull(qrCodeInfo.getTransAmt()) ? qrCodeInfo.getTransAmt() : "0.00");
        mchntOrderInfo.setRealSettleAmt(mchntOrderInfo.getOrderAmt());
        mchntOrderInfo.setRealSettleFlag(mchntInfo.getRealSettleFlag());
        // 静态码  银联返回的静态码值为1，返回结果静态码值为0
        Map<String, Object> orderExtraInfo = new HashMap<>();
        orderExtraInfo.put("qrCodeType", "0");

        //获取商户经纬度信息，静态码牌259上送商户经纬度信息
        TermInfo termInfo = new TermInfo();
        termInfo.setLongitude(mchntInfo.getMchntLng());
        termInfo.setLatitude(mchntInfo.getMchntLat());
        orderExtraInfo.put("termInfo", termInfo);
        orderExtraInfo.put("areaInfo", mchntInfo.getMchntBizRegion());
        mchntOrderInfo.setOrderExtraInfo(JSON.toJSONString(orderExtraInfo));
        mchntOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        mchntOrderInfo.setTermNo(qrCodeInfo.getQrNum());
        mchntOrderInfo.setTermType(McpsParamConstant.STATIC_QR_CODE_TYPE);
        //判断商户是否是独立清算的门店商户
        if ("11".equals(mchntInfo.getMchntType()) && AppParamConstant.NO.equals(mchntInfo.getIndependentDataFlag())) {
            rglog.debug("非独立维护资料的门店商户商户订单表记录其连锁商户号");
            mchntOrderInfo.setChainMchntNo(mchntInfo.getChainMchntNo());
        }
        mchntOrderList.add(mchntOrderInfo);
        return mchntOrderList;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        QrCodeInfoQueryResponse queryResponse = (QrCodeInfoQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(queryResponse);
    }

    /**
     * 获取二维码图片信息内容
     *
     * @param requeset 请求体
     * @param qrLogUrl 二维码url
     * @return 图片内容压缩
     * @throws Exception 异常
     */
    private String downImage(QrCodeInfoQueryRequeset requeset, String qrLogUrl) throws Exception {
        SysParamMapper sysParamMapper = new SysParamMapperImpl();
        SysParam localUrlPrefix = sysParamMapper.selectSysParamByPrimaryKey(requeset.getHeader().getInstId(), McpsParamConstant.IMAGE_STORAGE_PARAM_TYPE, McpsParamConstant.LOCAL_IMAGE_STORAGE_PATH);
        if (null == localUrlPrefix) {
            rglog.error("查询系统参数表，根据机构获取图片存储服务器路径为空！InstId：<{}>!", requeset.getHeader().getInstId());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        //共享文件夹路径
        String shareUrl;
        if (localUrlPrefix.getParamValue().trim().endsWith(File.separator)) {
            shareUrl = localUrlPrefix.getParamValue().trim();
        } else {
            shareUrl = localUrlPrefix.getParamValue().trim() + File.separator;
        }

        //文件存储的全路径
        String fileFullPath = shareUrl + qrLogUrl;
        rglog.info("商户二维码头像log全路径:<{}>", fileFullPath);

        //读取文件内容
        File downloadFile = new File(fileFullPath);
        if (!downloadFile.exists()) {
            rglog.error("文件<{}>不存在!", fileFullPath);
            return "";
        }

        FileInputStream fileInputStream = null;
        byte[] downloadFileBytes;
        try {
            fileInputStream = new FileInputStream(downloadFile);
            downloadFileBytes = new byte[fileInputStream.available()];
            fileInputStream.read(downloadFileBytes);
            fileInputStream.close();
        } catch (IOException ioe) {
            rglog.error(ioe.getMessage());
            throw ioe;
        } finally {
            if (null != fileInputStream) {
                try {
                    fileInputStream.close();
                } catch (IOException ignored) {
                }
            }
        }
        //压缩图片
        byte[] commpressImageData = ImageUtil.commpressPicForScale(downloadFileBytes, 20, 0.4);
        rglog.debug("压缩图片后的大小:<{}>", commpressImageData.length);

        //base64解压
        return Base64.encodeBase64String(commpressImageData);
    }
}
